<style lang='scss'>
html,
body {
  height: 100%;
}

body {
  background-color: #000000;
  margin: 0;
  font-family: Helvetica, sans-serif;
  overflow: hidden;
}

#product-select {
  position: relative;
  width: 100%;
  height: 100%;

  #prouduct-area {
    .element {
      box-shadow: 0px 0px 12px rgba(0, 255, 255, 0.5);
      border: 1px solid rgba(127, 255, 255, 0.25);
      text-align: center;
      cursor: default;

      & > :hover {
        box-shadow: 0px 0px 12px rgba(0, 255, 255, 0.75);
        border: 1px solid rgba(127, 255, 255, 0.75);
      }

      & > .symbol {
        position: absolute;
        top: 50px;
        left: 0px;
        right: 0px;
        font-size: 40px;
        font-weight: bold;
        color: rgba(255, 255, 255, 0.75);
        text-shadow: 0 0 10px rgba(0, 255, 255, 0.95);
      }
    }
  }

  // 形状切换
  #shape-switch {
    position: absolute;
    bottom: 20px;
    width: 100%;
    text-align: center;

    & > button {
      color: rgba(127, 255, 255, 0.75);
      background: transparent;
      outline: 1px solid rgba(127, 255, 255, 0.75);
      border: 0px;
      padding: 5px 10px;
      cursor: pointer;
    }
    & > button:hover {
      background-color: rgba(0, 255, 255, 0.5);
    }
    & > button:active,
    & > button.active {
      color: #795548;
      background-color: rgba(0, 255, 255, 0.75);
    }
  }
}
.product-area{
  background-color: rgb(36, 40, 42);
  box-shadow: 0 0 6px #cecece;
  color: rgba(255, 255, 255, 0.7);
  box-sizing: border-box;
  position: relative;
  transition: all 0.3s ease 0s;
  border-radius:4px;
  max-width: 100%;
  width: 1000px;
  min-height: 500px;
  top: 50%;
  left: 50%;
  /* width: 100%; */
  transform: translate(-50%,-50%);
  padding: 20px;
  h1{
    margin-left: 12px;
  }
  ul{
    display: flex;
    width: 100%;
    flex-direction: row;
    flex-wrap:wrap;
    li{
      width: 10%;
      height: 120px;
      line-height: 120px;
      text-align: center;
      margin: 10px;
      cursor: pointer;
      color: white;
      background-color: rgba(0, 0, 0, 0.2);
      transition: all 0.3s ease 0s;
      border-width: 2px;
      border-style: solid;
      border-color: rgba(0, 0, 0, 0.3);
      border-radius: 4px;
      outline: none;
      display: inline-block;
      //box-shadow: 0 0 3px #cecece, 1px 1px 0 #a7a2a2, 3px 1px 0 #cecece, 1px 1px 0 #cfcfcf;
      box-shadow: 0 0 4px #cecece, 1px 1px 0 #a7a2a2, 2px 1px 0 #cecece, 3px 1px 0 #cfcfcf, 4px 0 0 #cecece;
      &:hover{
        animation-name: wobble-horizontal;
        animation-duration: 1s;
        animation-timing-function: ease-in-out;
        animation-iteration-count: 1;
        background-color: rgba(223, 176, 122, 0.4);
        border-color: rgba(255, 255, 255, 0.1);
      }
    }
  }
}
/* Wobble Horizontal */
@keyframes wobble-horizontal {
  16.65% {
    transform: translateX(8px);
  }
  33.3% {
    transform: translateX(-6px);
  }
  49.95% {
    transform: translateX(4px);
  }
  66.6% {
    transform: translateX(-2px);
  }
  83.25% {
    transform: translateX(1px);
  }
  100% {
    transform: translateX(0);
  }
}
</style>
<template>
  <div id="product-select">
    <div class="product-area">
      <h1>请选择产品</h1>
      <ul>
        <li v-for="item in prouductData" :key="item" class="button wobble-horizontal" @click="goMain(item)">
          {{item}}
        </li>
      </ul>
    </div>
    <!-- <div id="prouduct-area"></div> -->
    <!-- <div id="shape-switch">
      <button id="table" class="active">表格</button>
      <button id="sphere">球形</button>
      <button id="helix">螺旋</button>
      <button id="grid">栅格</button>
    </div> -->
  </div>
</template>
<script>

import Vue from "vue"
import { mapGetters } from 'vuex';
import { isJSON, sendReq ,GetQueryString, changeURLArg, cookie} from "src/utils/tools";
export default {
  data() {
    return {
      prouductList: [],
      prouductData:[]
    };
  },
  computed: {},
  mounted() {
    // 设置展示形状切换的选中效果
    $('#shape-switch > button').click(function () {
      $(this).addClass('active').siblings().removeClass('active');
    })
    let pictureWall = ['three.min.js', 'tween.min.js', 'TrackballControls.js', 'CSS3DRenderer.js'];
    pictureWall = pictureWall.map((item, index) => {
      let dir = 'pictureWall';
      let basePath = `./static/js/${dir}/${item}`;
      return item = location.port == 50001 ? basePath : location.pathname + basePath;
    })
    new Promise((rs, rj) => {
      $.getScript(pictureWall[0]).done(() => { rs(); }).fail(() => rj());
    }).then(() => {
        return new Promise((rs, rj) => {
          sendReq({
            url: '/config/getProductCode',
            params: {},
            cb: (data) => {
              this.prouductData = data;
              this.prouductList = this.sortData(data);
              rs('ok');
            },
            error: () => {
              rj('error');
            }
          })
        })
      })
      .then(() => {
        return new Promise((rs, rj) => {
          $.getScript(pictureWall[1]).done(() => rs()).fail(() => rj());
        })
      })
      .then(() => {
        return new Promise((rs, rj) => {
          $.getScript(pictureWall[2]).done(() => rs()).fail(() => rj());
        })
      })
      .then(() => {
        $.getScript(pictureWall[3]).done(() => {
          window.CONTEXT = this;
          setTimeout(() => {
            //this.renderPictureWall(this.prouductList);
          }, 100)
        }).fail(() => { });
      })
  },
  methods: {
    goMain(item){
      cookie.set('isVisitedProduct', '24h', 24);
      if(item == "+"){
        this.addProduct();
        return;
      }else{
        //console.log(this.$router,'push')
        // window.CONTEXT.$router.push({ 
        //   path: 'main', 
        //   query: { productCode: item } 
        // });
        cookie.set('productCode', item, 24);
       
        this.$router.push({
          path: `/main/${item}`,
        })
        Vue.prototype.productCode = item;
      }
    },
    sortData(data) {
      let prouductList = [];
      const rowCount = 10;
      data.push('+');
      data && data.forEach((item, index) => {
        if (index < 2) {
          prouductList.push([item, index == 0 ? ((index + 1) % rowCount) : rowCount, Math.ceil((index + 1) / rowCount)])
        } else {
          // -2是因为前面排列了两个元素,从第3个元素起要换行 +1行是index从零开始,
          prouductList.push([item, ((index + 1 - 2) % rowCount == 0 ? rowCount : (index + 1 - 2) % rowCount), Math.ceil((index + 1 - 2) / rowCount) + 1])
        }
      })
      // console.log(prouductList);
      return prouductList;
    },
    addProduct() {
      this.$prompt('请输入产品编码', '添加产品', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /[\w\d]+/,
        inputErrorMessage: '产品编码格式不正确'
      }).then(({ value }) => {
        new Promise((rs, rj) => {
          sendReq({
            url: '/config/addProductCode',
            params: { productCode: value, content: '' },
            cb: (data) => {
              rs('ok')
            },
            error: () => {
              rj('error');
            }
          })
        }).then(() => {
          sendReq({
            url: '/config/getProductCode',
            params: {},
            cb: (data) => {
              // this.prouductList = this.sortData(data);
              // this.renderPictureWall(this.prouductList);
              this.prouductData = data;
            },
            error: () => {
            }
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消'
        });
      });
    },
    renderPictureWall(list, isRender) {
      var table = list ? list : [];

      var camera, scene, renderer;
      var controls;

      var objects = [];
      var targets = { table: [], sphere: [], helix: [], grid: [] };

      init();
      animate();

      function init() {

        camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 10000);
        camera.position.z = 3000;

        scene = new THREE.Scene();


        // 找出产品中最长的名称
        let max = table[0][0].length;
        for (let i = 0, len = table.length; i < len - 1; i++) {
          max = max < table[i + 1][0].length ? table[i + 1][0].length : max
        }

        // 计算每个产品绘制的宽度
        let eleWidth = max * 26;

        // console.log(eleWidth);


        for (var i = 0; i < table.length; i++) {

          var element = document.createElement('div');
          element.className = 'element';
          element.style.width = eleWidth + 'px';
          // element.style.width = '140px';
          element.style.height = '160px';
          element.style.backgroundColor = 'rgba(0,127,127,' + (Math.random() * 0.5 + 0.25) + ')';

          // var number = document.createElement('div');
          // number.className = 'number';
          // number.textContent = (i / 5) + 1;
          // element.appendChild(number);

          var symbol = document.createElement('div');
          symbol.className = 'symbol';
          symbol.textContent = table[i][0];
          element.appendChild(symbol);

          // var details = document.createElement('div');
          // details.className = 'details';
          // details.innerHTML = table[i + 1] + '<br>' + table[i + 2];
          // element.appendChild(details);

          var object = new THREE.CSS3DObject(element);
          object.position.x = Math.random() * 4000 - 2000;
          object.position.y = Math.random() * 4000 - 2000;
          object.position.z = Math.random() * 4000 - 2000;
          scene.add(object);

          objects.push(object);

          let count = table.length;
          var object = new THREE.Object3D();

          // 每行排列十八个元素 
          object.position.x = (table[i][1] * eleWidth) - eleWidth * (10 + 1) / 2;
          // table[i][2] * 200 调整y轴距离
          object.position.y = - (table[i][2] * 200) + (990 - 320);



          targets.table.push(object);

        }

        // console.log(targets.table);
        // sphere

        var vector = new THREE.Vector3();

        for (var i = 0, l = objects.length; i < l; i++) {

          var phi = Math.acos(-1 + (2 * i) / l);
          var theta = Math.sqrt(l * Math.PI) * phi;

          var object = new THREE.Object3D();

          object.position.x = 800 * Math.cos(theta) * Math.sin(phi);
          object.position.y = 800 * Math.sin(theta) * Math.sin(phi);
          object.position.z = 800 * Math.cos(phi);

          vector.copy(object.position).multiplyScalar(2);

          object.lookAt(vector);

          targets.sphere.push(object);

        }

        // helix

        var vector = new THREE.Vector3();

        for (var i = 0, l = objects.length; i < l; i++) {

          var phi = i * 0.175 + Math.PI;

          var object = new THREE.Object3D();

          object.position.x = 900 * Math.sin(phi);
          object.position.y = - (i * 8) + 450;
          object.position.z = 900 * Math.cos(phi);

          vector.x = object.position.x * 2;
          vector.y = object.position.y;
          vector.z = object.position.z * 2;

          object.lookAt(vector);

          targets.helix.push(object);

        }

        // grid

        for (var i = 0; i < objects.length; i++) {

          var object = new THREE.Object3D();

          object.position.x = ((i % 3) * 400) - 800;
          object.position.y = (- (Math.floor(i / 3) % 3) * 400) + 1000;
          object.position.z = (Math.floor(i / 9)) * 1000 - 2000;

          targets.grid.push(object);

        }

        //

        renderer = new THREE.CSS3DRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.domElement.style.position = 'absolute';
        let prouductArea = document.getElementById('prouduct-area');
        $('#prouduct-area').html('');

        prouductArea.appendChild(renderer.domElement);

        // 点击某个产品后,进行跳转
        prouductArea.addEventListener('click', function (ev) {

          var ev = ev || window.event;
          var target = ev.target || ev.srcElement;
          // 扩大焦点
          if (target.className.toLowerCase() == 'element' || target.className.toLowerCase() == 'symbol') {
            cookie.set('isVisitedProduct', '24h', 24);
            if (target.innerText != '+') {
              // 将产品编码带过去
              window.CONTEXT.$router.push({ path: 'main', query: { productCode: target.innerText } });
              cookie.set('productCode', target.innerText, 24);
            } else {
              window.CONTEXT.addProduct();
            }
            // console.log(target.innerText);
          }

        }, false);


        controls = new THREE.TrackballControls(camera, renderer.domElement);
        controls.rotateSpeed = 0.5;
        controls.minDistance = 500;
        controls.maxDistance = 6000;
        controls.addEventListener('change', render);


        var button = document.getElementById('table');
        button.addEventListener('click', function (event) {

          transform(targets.table, 2000);

        }, false);

        var button = document.getElementById('table');
        button.addEventListener('click', function (event) {

          transform(targets.table, 2000);

        }, false);

        var button = document.getElementById('sphere');
        button.addEventListener('click', function (event) {

          transform(targets.sphere, 2000);

        }, false);

        var button = document.getElementById('helix');
        button.addEventListener('click', function (event) {

          transform(targets.helix, 2000);

        }, false);

        var button = document.getElementById('grid');
        button.addEventListener('click', function (event) {

          transform(targets.grid, 2000);

        }, false);

        transform(targets.table, 5000);

        //

        window.addEventListener('resize', onWindowResize, false);

      }

      function transform(targets, duration) {

        TWEEN.removeAll();

        for (var i = 0; i < objects.length; i++) {

          var object = objects[i];
          var target = targets[i];

          new TWEEN.Tween(object.position)
            .to({ x: target.position.x, y: target.position.y, z: target.position.z }, Math.random() * duration + duration)
            .easing(TWEEN.Easing.Exponential.InOut)
            .start();

          new TWEEN.Tween(object.rotation)
            .to({ x: target.rotation.x, y: target.rotation.y, z: target.rotation.z }, Math.random() * duration + duration)
            .easing(TWEEN.Easing.Exponential.InOut)
            .start();

        }

        new TWEEN.Tween(this)
          .to({}, duration * 2)
          .onUpdate(render)
          .start();

      }

      function onWindowResize() {

        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();

        renderer.setSize(window.innerWidth, window.innerHeight);

        render();

      }

      function animate() {

        requestAnimationFrame(animate);

        TWEEN.update();

        controls.update();

      }

      function render() {

        renderer.render(scene, camera);

      }


    },
  }
}

</script>